// pages/index/realTimeData/realtime.js
const app = getApp()
const utils = require('../../../utils/util')
const api = require("../../../utils/api")
const bluetoothUtils = require("../../../utils/bluetoothUtils")
Page({

    /**
     * 页面的初始数据
     */
    data: {
        realTimeData: {
            heart_left: '--',
            breath_left: '--',
            twitch_left: '--',
            heart_right: '--',
            breath_right: '--',
            twitch_right: '--'
        },
        leftFlag: true,
        rightFlag: false,
        sum1: 0,
        sum2: 0,
        bedside: 0,
        realTimeDataId: null,
        listener: null
    },
    // buffer转16进制
    ab2hex: function (buffer) {
        let hexArr = Array.prototype.map.call(
            new Uint8Array(buffer),
            function (bit) {
                return ('00' + bit.toString(16)).slice(-2)
            }
        )
        return hexArr.join('');
    },

    //实时数据具体方法。按字节取反，依次取值
    getRealTimeData: function () {
        let _this = this
        console.log('bedside==========>', app.globalData.bedside)
        // this.Read()
        console.log('getRealTimeData')
        let listener = function (res) {
            console.log('res====>', res)
            var realTimeData = _this.ab2hex(res.value)
            console.log("接受实时数据===》", realTimeData)
            if (realTimeData.substring(0, 4) == 'ffaa' && realTimeData.length > 30) {
                let realData = realTimeData.substring(20, 18) + realTimeData.substring(18, 16) + realTimeData.substring(16, 14) + realTimeData.substring(14, 12)
                console.log("realData======>", realData)
                let binaryData = utils.hexToBinary(realData)
                console.log("binaryData====>", binaryData)
                let hr = parseInt(binaryData.substr(-9, 9), 2).toString(10)
                let br = parseInt(binaryData.substr(-16, 7), 2).toString(10)
                let turn = parseInt(binaryData.substr(-32, 4), 2).toString(10)
                let leave = parseInt(binaryData.substr(-18, 2), 2).toString(10)
                let side = parseInt(utils.hexToBinary(realTimeData.substring(5, 6)), 2).toString(10)
                console.log("边", side, "心率", hr, "呼吸", br, "离床", leave, "\n\n")
                if (leave == 0) { //离床 0-在床 1-离床
                    if (app.globalData.bedside == 1) {
                        _this.data.realTimeData.twitch_left = 0
                        let sum = _this.data.realTimeData.twitch_left
                        _this.setData({
                            'realTimeData.heart_left': hr,
                            'realTimeData.breath_left': br,
                            'realTimeData.twitch_left': parseInt(turn) + sum,
                        })
                    } else if (app.globalData.bedside == 0) {
                        _this.data.realTimeData.twitch_right = 0
                        let sum = _this.data.realTimeData.twitch_right
                        _this.setData({
                            'realTimeData.heart_right': hr,
                            'realTimeData.breath_right': br,
                            'realTimeData.twitch_right': parseInt(turn) + sum,
                        })
                    } else {
                        console.log('blue1====>', app.globalData.bluetoothInfo)
                        console.log('blue1====>', app.globalData.bluetoothInfo2)
                        console.log('res.deviceId====>', res.deviceId)
                        if (res.deviceId == app.globalData.bluetoothInfo.deviceID) {
                            let sum = _this.data.realTimeData.twitch_left == '--' ? 0 : _this.data.realTimeData.twitch_left
                            _this.setData({
                                'realTimeData.heart_left': hr,
                                'realTimeData.breath_left': br,
                                'realTimeData.twitch_left': parseInt(turn) + sum,
                            })
                        } else {
                            let sum = _this.data.realTimeData.twitch_right == '--' ? 0 : _this.data.realTimeData.twitch_right
                            _this.setData({
                                'realTimeData.heart_right': hr,
                                'realTimeData.breath_right': br,
                                'realTimeData.twitch_right': parseInt(turn) + sum,
                            })
                        }
                    }
                } else { //离床数据直接清空列表
                    if (app.globalData.bedside == 1) {
                        _this.setData({
                            'realTimeData.heart_left': '--',
                            'realTimeData.breath_left': '--',
                            'realTimeData.twitch_left': '--',
                        })
                    }
                    if (app.globalData.bedside == 0) {
                        _this.setData({
                            'realTimeData.heart_right': '--',
                            'realTimeData.breath_right': '--',
                            'realTimeData.twitch_right': '--',
                        })
                    }
                }
            }
        }
        this.setData({
            listener: listener
        })
        wx.onBLECharacteristicValueChange(listener)
    },
    //开始实时数据
    startRealTimeData() {
        let _this = this
        console.log('startRealTimeData')
        clearInterval(_this.data.realTimeDataId)
        _this.data.realTimeDataId = setInterval(function () {
            console.log('test11111111111')
            _this.getRealTimeData()

        }, 10000)
    },
    //获取绑定床边
    getUserInfo() {
        let data = {
            user_id: app.globalData.userId
        }
        //   util.myShowLoading('用户信息加载中')
        api.getBindInfo(data, app.globalData.token).then(res => {
            util.myHideLoading()
            if (res.data.code == 200) {
                console.log('res', res)
                let hoteldata = res.data.data
                if (hoteldata.device_id != undefined) {
                    if (hoteldata.bed_side == 1) {
                        this.setData({
                            leftFlag: true,
                            rightFlag: false
                        })
                    } else if (hoteldata.bed_side == 0) {
                        this.setData({
                            rightFlag: true,
                            leftFlag: false
                        })
                    } else {
                        this.setData({
                            leftFlag: true,
                            rightFlag: true
                        })
                    }
                }
            } else {
                util.myShowToast('服务器有点小问题')
            }
        })
    },
    /**
     * 生命周期函数--监听页面加载
     */
    onLoad(options) {},

    /**
     * 生命周期函数--监听页面初次渲染完成
     */
    onReady() {

    },

    /**
     * 生命周期函数--监听页面显示
     */
    onShow() {
        let _this = this
        // bluetoothUtils.oneTouchConnectBluetooth(app.globalData.deviceId)
        // app.watchProperty(_this.bluetooth, 'bluetooth_connected', false)
        let data = {
            user_id: app.globalData.userId
        }
        api.getBindInfo(data, app.globalData.token).then(res => {
            if (res.data.code == 200) {
                if (res.data.data.bed_side == 0) {
                    app.globalData.bedside = 0
                    this.setData({
                        leftFlag: false,
                        rightFlag: true
                    })
                } else if (res.data.data.bed_side == 1) {
                    app.globalData.bedside = 1
                    this.setData({
                        leftFlag: true,
                        rightFlag: false
                    })
                } else {
                    //一人睡双床
                    app.globalData.bedside = 2
                    this.setData({
                        leftFlag: true,
                        rightFlag: true
                    })
                }
            }
        })
        setTimeout(() => {
            if (app.globalData.bluetooth_connected != false) {
                _this.startRealTimeData() //开始实时数据
            }
        }, 5000)

    },

    /**
     * 生命周期函数--监听页面隐藏
     */
    onHide() {
        clearInterval(this.data.realTimeDataId)
        this.setData({
            realTimeDataId: null,
            realTimeData: {
                heart_left: '--',
                breath_left: '--',
                twitch_left: '--',
                heart_right: '--',
                breath_right: '--',
                twitch_right: '--'
            },
        })
        let _this = this
        wx.offBLECharacteristicValueChange(_this.data.listener)
    },

    /**
     * 生命周期函数--监听页面卸载
     */
    onUnload() {
        clearInterval(this.data.realTimeDataId)
        this.setData({
            realTimeDataId: null,
            realTimeData: {
                heart_left: '--',
                breath_left: '--',
                twitch_left: '--',
                heart_right: '--',
                breath_right: '--',
                twitch_right: '--'
            },
        })
        let _this = this
        console.log('listener', _this.data.listener)
        wx.offBLECharacteristicValueChange(_this.data.listener)
    },

    /**
     * 页面相关事件处理函数--监听用户下拉动作
     */
    onPullDownRefresh() {

    },

    /**
     * 页面上拉触底事件的处理函数
     */
    onReachBottom() {

    },

    /**
     * 用户点击右上角分享
     */
    onShareAppMessage() {

    }
})